<template>
  <div class="customer-tracking-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="4">
        <el-button :icon="Plus" type="primary" @click="ApplyPick">
          申请挑入客户
        </el-button>
        <!-- <el-button :icon="Delete" type="danger" @click="handleDelete">
          批量放弃跟进
        </el-button> -->
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="20">
        <el-form :inline="true" :model="queryForm" @submit.prevent>
          <el-space>
            <el-form-item>
              <el-cascader
                v-model="queryForm.searchCompany"
                :options="CompanyOptions"
                :props="companyProps"
                clearable
                collapse-tags
                placeholder="选择组织"
                style="width: 200px"
                @change="getDeptment"
              />
            </el-form-item>
            <el-form-item>
              <el-cascader
                v-model="queryForm.searchDeptment"
                :options="DeptmentOptions"
                :props="deptmentProps"
                clearable
                collapse-tags
                placeholder="选择部门"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item class="form-item">
              <el-cascader
                v-model="queryForm.searchProductClass"
                :options="ProductClassOptions"
                :props="ProductClassSelect"
                placeholder="选择业务类型"
                clearable
                style="width: 160px"
              />
            </el-form-item>
            <el-form-item>
              <el-input
                v-model.trim="queryForm.saleStaff"
                clearable
                placeholder="按跟进人"
                style="width: 100px"
              />
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="queryForm.trackLevel"
                placeholder="按成熟度"
                clearable
                style="width: 100px"
              >
                <el-option label="A" value="A" />
                <el-option label="B" value="B" />
                <el-option label="C" value="C" />
                <el-option label="D" value="D" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="queryForm.trackType"
                placeholder="按跟进方式"
                clearable
                style="width: 130px"
              >
                <el-option label="电话" :value="1" />
                <el-option label="上门" :value="2" />
                <el-option label="客户到公司" :value="3" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="queryForm.NextTrackDate"
                style="width: 240px"
                type="daterange"
                placeholder="下次跟进时间"
                start-placeholder="下次跟进时间起"
                end-placeholder="下次跟进时间止"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item>
              <el-input
                v-model.trim="queryForm.searchKey"
                clearable
                placeholder="请输入客户名称"
                style="width: 120px"
                @input="trimkey"
              />
            </el-form-item>
            <el-form-item>
              <el-button :icon="Search" type="primary" @click="queryData">
                查询
              </el-button>
            </el-form-item>
          </el-space>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>
    <el-tabs
      :model-value="queryForm.tab"
      type="border-card"
      @tab-click="handleTabClick"
    >
      <el-tab-pane label="跟进中" name="tracking">
        <el-table
          v-loading="listLoading"
          :data="list"
          @selection-change="setSelectRows"
        >
          <el-table-column
            align="center"
            show-overflow-tooltip
            type="selection"
          />
          <el-table-column
            align="center"
            label="公海ID"
            prop="CustomerID"
            show-overflow-tooltip
            width="80"
          />
          <el-table-column
            align="center"
            label="挑入ID"
            prop="CustomerPickID"
            show-overflow-tooltip
            width="80"
          />
          <el-table-column
            align="left"
            label="客户名称"
            prop="CustomerAllName"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="商机ID"
            prop="OrderID"
            show-overflow-tooltip
            width="80"
          />
          <el-table-column
            align="center"
            label="挑入时间"
            show-overflow-tooltip
            width="120"
          >
            <template #default="{ row }">
              {{ row.addTime.split(' ')[0] }}
              <br />
              {{ row.addTime.split(' ')[1] }}
            </template>
          </el-table-column>
          <el-table-column
            align="left"
            label="跟进商机名称"
            prop="BusinessOrderName"
            show-overflow-tooltip
          />
          <el-table-column align="center" label="跟进小记" width="200">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                plain
                @click="getTrackRecord(row)"
              >
                跟进小记（{{ row.TrackRecordCount }} 条）
              </el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" label="最后跟进时间" width="120">
            <template #default="{ row }">
              {{ row.LastTrackTime.split(' ')[0] }}
              <br />
              {{ row.LastTrackTime.split(' ')[1] }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="成熟度" width="120">
            <template #default="{ row }">
              <div v-if="row.TrackLevel">
                {{ row.TrackLevel }}
              </div>
              <div v-else>
                {{ row.LastTrack?.TrackLevel }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="跟进方式" width="120">
            <template #default="{ row }">
              <div v-if="row.TrackType">
                <span v-if="row.TrackType === 1">电话</span>
                <span v-if="row.TrackType === 2">上门</span>
                <span v-if="row.TrackType === 3">客户到公司</span>
              </div>
              <div v-else>
                <span v-if="row.LastTrack?.TrackType === 1">电话</span>
                <span v-if="row.LastTrack?.TrackType === 2">上门</span>
                <span v-if="row.LastTrack?.TrackType === 3">客户到公司</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="下次跟进时间" width="120">
            <template #default="{ row }">
              {{ row.NextTrackTime }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="180">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="getCustomerTrack(row)"
              >
                客户跟进
              </el-button>
              <el-button type="primary" size="small" @click="handleDelete(row)">
                放弃跟进
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          :current-page="queryForm.pageNo"
          :layout="layout"
          :page-size="queryForm.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </el-tab-pane>
      <el-tab-pane
        v-if="loginUser.StaffPostRoleID !== 8"
        label="下属跟进中"
        name="subTracking"
      >
        <el-table
          v-loading="listLoading"
          :data="list"
          @selection-change="setSelectRows"
        >
          <el-table-column
            align="center"
            show-overflow-tooltip
            type="selection"
          />
          <el-table-column
            align="center"
            label="公海ID"
            prop="CustomerID"
            show-overflow-tooltip
            width="80"
          />
          <el-table-column
            align="center"
            label="跟进人"
            prop="SaleStaffName"
            show-overflow-tooltip
            width="80"
          />
          <el-table-column
            align="center"
            label="挑入ID"
            prop="CustomerPickID"
            show-overflow-tooltip
            width="80"
          />
          <el-table-column
            align="left"
            label="客户名称"
            prop="CustomerAllName"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="商机ID"
            prop="OrderID"
            show-overflow-tooltip
            width="80"
          />
          <el-table-column
            align="center"
            label="挑入时间"
            show-overflow-tooltip
            width="120"
          >
            <template #default="{ row }">
              {{ row.addTime.split(' ')[0] }}
              <br />
              {{ row.addTime.split(' ')[1] }}
            </template>
          </el-table-column>
          <el-table-column
            align="left"
            label="跟进商机名称"
            prop="BusinessOrderName"
            show-overflow-tooltip
          />
          <el-table-column align="center" label="跟进小记" width="200">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                plain
                @click="getTrackRecord(row)"
              >
                跟进小记（{{ row.TrackRecordCount }} 条）
              </el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" label="最后跟进时间" width="120">
            <template #default="{ row }">
              {{ row.LastTrackTime.split(' ')[0] }}
              <br />
              {{ row.LastTrackTime.split(' ')[1] }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="成熟度" width="120">
            <template #default="{ row }">
              <div v-if="row.TrackLevel">
                {{ row.TrackLevel }}
              </div>
              <div v-else>
                {{ row.LastTrack?.TrackLevel }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="跟进方式" width="120">
            <template #default="{ row }">
              <div v-if="row.TrackType">
                <span v-if="row.TrackType === 1">电话</span>
                <span v-if="row.TrackType === 2">上门</span>
                <span v-if="row.TrackType === 3">客户到公司</span>
              </div>
              <div v-else>
                <span v-if="row.LastTrack?.TrackType === 1">电话</span>
                <span v-if="row.LastTrack?.TrackType === 2">上门</span>
                <span v-if="row.LastTrack?.TrackType === 3">客户到公司</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="下次跟进时间" width="120">
            <template #default="{ row }">
              {{ row.NextTrackTime }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="180">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="getCustomerTrack(row)"
              >
                客户跟进
              </el-button>
              <el-button type="primary" size="small" @click="handleDelete(row)">
                放弃跟进
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          :current-page="queryForm.pageNo"
          :layout="layout"
          :page-size="queryForm.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </el-tab-pane>
      <el-tab-pane :label="giveName" name="subGived">
        <el-table
          v-loading="listLoading"
          :data="list"
          @selection-change="setSelectRows"
        >
          <el-table-column
            align="center"
            show-overflow-tooltip
            type="selection"
          />
          <el-table-column
            align="center"
            label="公海ID"
            prop="CustomerID"
            show-overflow-tooltip
            width="80"
          />
          <el-table-column
            align="center"
            label="跟进人"
            prop="SaleStaffName"
            show-overflow-tooltip
            width="80"
          />
          <el-table-column
            align="center"
            label="挑入ID"
            prop="CustomerPickID"
            show-overflow-tooltip
            width="80"
          />
          <el-table-column
            align="left"
            label="客户名称"
            prop="CustomerAllName"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="商机ID"
            prop="OrderID"
            show-overflow-tooltip
            width="80"
          />
          <el-table-column
            align="center"
            label="挑入时间"
            show-overflow-tooltip
            width="120"
          >
            <template #default="{ row }">
              {{ row.addTime.split(' ')[0] }}
              <br />
              {{ row.addTime.split(' ')[1] }}
            </template>
          </el-table-column>
          <el-table-column
            align="left"
            label="跟进商机名称"
            prop="BusinessOrderName"
            show-overflow-tooltip
          />
          <!-- <el-table-column align="center" label="跟进小记" width="200">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                plain
                @click="getTrackRecord(row)"
              >
                跟进小记（{{ row.TrackRecordCount }} 条）
              </el-button>
            </template>
          </el-table-column> -->
          <el-table-column align="center" label="最后跟进时间" width="120">
            <template #default="{ row }">
              {{ row.LastTrackTime.split(' ')[0] }}
              <br />
              {{ row.LastTrackTime.split(' ')[1] }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="成熟度" width="120">
            <template #default="{ row }">
              {{ row.LastTrack?.TrackLevel }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="跟进方式" width="120">
            <template #default="{ row }">
              <span v-if="row.LastTrack?.TrackType === 1">电话</span>
              <span v-if="row.LastTrack?.TrackType === 2">上门</span>
              <span v-if="row.LastTrack?.TrackType === 3">客户到公司</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="180">
            <template #default="{ row }">
              <el-button
                type="info"
                size="small"
                @click="getCustomerTrack(row)"
              >
                已放弃
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          :current-page="queryForm.pageNo"
          :layout="layout"
          :page-size="queryForm.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </el-tab-pane>
    </el-tabs>
    <!-- <edit ref="editRef" @fetch-data="fetchData" /> -->
    <TrackRecord ref="recordRef" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import {
    // getOpenAreaCity,
    BusinessClassSelect,
    getMyCompanySelect,
    getMyDeptmentSelect,
  } from '@/api/common'
  import { getList, doDelete } from '@/api/customerTracking'
  // import Edit from './components/CustomerTrackingEdit'
  import TrackRecord from '@/views/business/components/TrackRecord'
  import { Delete, Plus, Search } from '@element-plus/icons-vue'

  export default defineComponent({
    name: 'Tracking',
    components: { TrackRecord },
    setup() {
      const router = useRouter()
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        loginUser: {},
        giveName: '',
        editRef: null,
        recordRef: null,
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        ProductClassOptions: [],
        DeptmentOptions: [],
        CompanyOptions: [],
        companyProps: {
          multiple: true,
          // checkStrictly: true,
          expandTrigger: 'hover',
        },
        deptmentProps: {
          multiple: true,
          // checkStrictly: true,
          expandTrigger: 'hover',
        },
        ProductClassSelect: {
          multiple: true,
          expandTrigger: 'hover',
        },
        queryForm: {
          pageNo: 1,
          pageSize: 10,
          searchKey: '',
          tab: 'tracking',
        },
      })
      const trimkey = (val) => {
        state.queryForm.searchKey = val.replace(
          /[^\u4e00-\u9fa5a-zA-Z0-9]/g,
          ''
        )
      }
      const setSelectRows = (val) => {
        state.selectRows = val
      }

      const handleTabClick = (tab) => {
        state.queryForm.tab = tab.props.name
        fetchData()
      }

      const ApplyPick = () => {
        router.push({
          path: '/customer/searchPick',
          query: {},
        })
      }
      const getTrackRecord = (row) => {
        const order = {
          CustomerPickID: row.CustomerPickID,
          OrderID: row.OrderID,
          TrackClass: [0],
        }
        state.recordRef.handleEdit(order)
      }
      const getCustomerTrack = (row) => {
        router.push({
          path: '/customer/track/trackingBusiness',
          query: { CustomerPickID: row.CustomerPickID },
        })
      }

      const handleEdit = (row) => {
        if (row.id) {
          state.editRef.showEdit(row)
        } else {
          state.editRef.showEdit()
        }
      }
      const handleDelete = (row) => {
        if (row.OrderID) {
          $baseConfirm('你确定要放弃跟进此商机吗', null, async () => {
            const { msg } = await doDelete({ ids: row.OrderID })
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            await fetchData()
          })
        } else {
          if (state.selectRows.length > 0) {
            const ids = state.selectRows.map((item) => item.OrderID).join()
            $baseConfirm('你确定要批量放弃跟进吗', null, async () => {
              const { msg } = await doDelete({ ids })
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              await fetchData()
            })
          } else {
            $baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      }

      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      const handleCurrentChange = (val) => {
        state.queryForm.pageNo = val
        fetchData()
      }
      const queryData = () => {
        state.queryForm.pageNo = 1
        fetchData()
      }
      const fetchData = async () => {
        state.listLoading = true
        const {
          data: { CompanyOptions },
        } = await getMyCompanySelect()
        state.CompanyOptions = CompanyOptions
        const {
          data: { BusinessClassOptions },
        } = await BusinessClassSelect()
        state.ProductClassOptions = BusinessClassOptions
        const {
          data: { list, total },
        } = await getList(state.queryForm)
        state.list = list
        state.total = total
        state.listLoading = false
      }
      const getDeptment = async () => {
        console.log('form.Company', state.queryForm.searchCompany)
        if (state.queryForm.searchCompany) {
          const getParams = {
            CompanyID: state.queryForm.searchCompany,
          }
          const {
            data: { DeptmentOptions },
          } = await getMyDeptmentSelect(getParams)
          state.DeptmentOptions = DeptmentOptions
        } else {
          state.queryForm.searchDeptment = []
          state.DeptmentOptions = []
        }
      }
      onMounted(() => {
        state.loginUser = JSON.parse(localStorage.getItem('userInfo'))
        if (state.loginUser.StaffPostRoleID == 8) {
          state.giveName = '已放弃'
        } else {
          state.giveName = '下属已放弃'
        }
        fetchData()
      })

      return {
        ...toRefs(state),
        setSelectRows,
        ApplyPick,
        getTrackRecord,
        handleTabClick,
        getCustomerTrack,
        handleEdit,
        handleDelete,
        handleSizeChange,
        handleCurrentChange,
        queryData,
        fetchData,
        Delete,
        Plus,
        Search,
        trimkey,
        getDeptment,
      }
    },
  })
</script>
